import { useKeyPress } from 'ahooks';
import { useDispatch } from 'react-redux';
import {
  deleteComponent,
  copySelectedComponent,
  pasteComponent,
  selectPreComponent,
  selectNextComponent,
} from '../store/componentReducer';
import { ActionCreators } from 'redux-undo';
function isActiveElementValid() {
  if (document.activeElement === document.body) return true;
  if (document.activeElement?.matches('div[role="button"]')) return true;
  return false;
}
function useBindCanvasKeyPress() {
  const dispatch = useDispatch();
  useKeyPress(['backspace', 'delete'], () => {
    if (!isActiveElementValid()) {
      return;
    }
    dispatch(deleteComponent());
  });

  useKeyPress(['ctrl.c', 'meta.c'], () => {
    if (!isActiveElementValid()) {
      return;
    }
    dispatch(copySelectedComponent());
  });
  useKeyPress(['ctrl.v', 'meta.v'], () => {
    if (!isActiveElementValid()) {
      return;
    }
    dispatch(pasteComponent());
  });
  //选中上一个
  useKeyPress('uparrow', () => {
    if (!isActiveElementValid()) {
      return;
    }
    dispatch(selectPreComponent());
  });
  useKeyPress('downarrow', () => {
    if (!isActiveElementValid()) {
      return;
    }
    dispatch(selectNextComponent());
  });

  useKeyPress(
    ['ctrl.z', 'meta.z'],
    () => {
      if (!isActiveElementValid()) {
        return;
      }
      dispatch(ActionCreators.undo());
    },
    {
      exactMatch: true,
    },
  );

  useKeyPress(['ctrl.shift.z', 'meta.shift.z'], () => {
    if (!isActiveElementValid()) {
      return;
    }
    dispatch(ActionCreators.redo());
  });
}
export default useBindCanvasKeyPress;
